# coding:utf-8
from .AbstractPicComparator import AbstractPicComparator
import hashlib
from functools import partial

class Md5PicComparator(AbstractPicComparator):
    _hash_dict = {}
    _filecount = 0

    def __init__(self):
        pass
    
    @classmethod
    def _md5_sum(cls, filepath):
        with open(filepath, 'rb') as f:
            d = hashlib.md5()
            for buf in iter(partial(f.read, 128), b''):
                d.update(buf)
        return d.hexdigest()


    def compare(self, path1, path2):
        dig1 = self._md5_sum(path1)
        dig2 = self._md5_sum(path2)
        return (dig1 == dig2)

    def bingo(self, filepath):
        # print 'filepath = %s' % filepath
        if (filepath is None) or (len(filepath) == 0):
            print 'path cannot be empty'
            return -1;

        self._filecount += 1

        md5_hash = self._md5_sum(filepath)
        if (md5_hash is None) or (len(md5_hash) == 0):
            print 'generate md5_hash failed'
            return -1;

        path_array = self._hash_dict.get(md5_hash)
        if path_array is None:
            self._hash_dict[md5_hash] = [filepath]
        else:
            path_array.append(filepath)

    def report(self):
        duplicate_path_array = self._duplicate_path_array()
        print 'file count:%d duplicate:%d' % (self._filecount, len(duplicate_path_array))
        return (duplicate_path_array)

    def _duplicate_path_array(self):
        duplicate_array = []
        for (md5_hash, path_array) in self._hash_dict.items():
            if len(path_array) > 1:
                duplicate_array.append(path_array)
        return duplicate_array

